package com.ziyun.pop.web.modules.order.controller;

import com.service.ucenter.api.UserAccessoryService;
import com.utility.http.HttpUtils;
import com.ziyun.pop.common.utils.JsonUtils;
import com.ziyun.pop.modules.order.entity.UserAccessoryVo;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import io.renren.common.validator.ValidatorUtils;
import io.renren.modules.sys.entity.SysUserEntity;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 我的附件
 *
 * @author gaosheng
 * @email
 * @date 2018-09-01 10:02:31
 */
@RestController
@RequestMapping("order/useraccessory")
public class UserAccessoryController {


	@Value("${erpApi}")
	private String erpApi ;
	@Value("${oss.host}")
	private String ossHost;



/*	*//**
	 * 列表
	 *//*
	@RequestMapping("/list")
	@RequiresPermissions("order:useraccessory:list")
	public R list(@RequestParam Map<String, Object> params) {
		PageUtils page = userAccessoryService.queryPage(params);

		return R.ok().put("page", page);
	}

	*//**
	 * 信息
	 *//*
	@RequestMapping("/info/{id}")
	@RequiresPermissions("order:useraccessory:info")
	public R info(@PathVariable("id") Integer id) {
		UserAccessoryEntity userAccessory = userAccessoryService.selectById(id);

		return R.ok().put("userAccessory", userAccessory);
	}

	/**
	 * 修改
	 */
	/*@RequestMapping("/update")
	@RequiresPermissions("order:useraccessory:update")
	public R update(@RequestBody UserAccessoryEntity userAccessory) {
		ValidatorUtils.validateEntity(userAccessory);
		userAccessoryService.updateAllColumnById(userAccessory);// 全部更新

		return R.ok();
	}*/

	 /**
	 * 查询附件
	 * 
	 * @param itemId
	 *            订单商品ID
	 * @return
	 */
	@RequestMapping("/userAccessorys/{itemId}")
	public R userAccessorys(@PathVariable("itemId") String itemId) {
		Map<String, Object> paramBodyMap = new HashMap<String, Object>();
		paramBodyMap.put("itemId",itemId);
		String url = erpApi + "/order/useraccessory/userAccessorys";
		String response =  HttpUtils.doPost(url,paramBodyMap);
		R rs = JsonUtils.string2Object(response, R.class);
		return rs;
	}
	
	
	/**
	 * @author   Alix_zw
	 * @Date order/useraccessory/userAccessorysByOrder/
	 * @Description   通过订单号查询附件
	 
	 * @Return    
	**/
	@RequestMapping("/userAccessorysByOrder/{orderNo}")
	public R userAccessoryss(@PathVariable("orderNo") String orderNo) {
		Map<String,Object> mapByorderNo = new HashMap<>();
		mapByorderNo.put("orderNo",orderNo);
		String url = erpApi + "/order/useraccessory/userAccessorysByOrderNo";
		String response = HttpUtils.doPost(url,mapByorderNo);
		R r = JsonUtils.string2Object(response, R.class);
		return r;
	}

	/**
	 * 添加附件
	 * 
	 * @param userAccessoryVo
	 * @return
	 */
	@RequestMapping("/save")
	public R save(@RequestBody UserAccessoryVo userAccessoryVo) {
		Map<String, Object> paramBodyMap = new HashMap<String, Object>();
		// 获取当前登陆用户ID
		Long userId = ((SysUserEntity) SecurityUtils.getSubject().getPrincipal()).getUserId();
		paramBodyMap.put("userAccessoryVo",JsonUtils.object2String(userAccessoryVo));
		paramBodyMap.put("userId",userId);
		String url = erpApi + "/order/useraccessory/save";
		String response =  HttpUtils.doPost(url,paramBodyMap);
		R rs = JsonUtils.string2Object(response, R.class);
		return rs;
	}

	/**
	 * 删除附件
	 */
	@RequestMapping("/delete")
	public R delete(@RequestBody Integer[] ids) {
		Map<String, Object> paramBodyMap = new HashMap<String, Object>();
		paramBodyMap.put("ids",JsonUtils.object2String(ids));
		String url = erpApi + "/order/useraccessory/delete";
		String response =  HttpUtils.doPost(url,paramBodyMap);
		R rs = JsonUtils.string2Object(response, R.class);
		return rs;
	}

	/**
	 * 附件下载
	 * 
	 * @param id
	 * @param
	 * @param
	 */
	@RequestMapping("/download/{id}")
	public void uploadAccessorys(@PathVariable("id") Integer id, HttpServletRequest request,
								 HttpServletResponse response) {
		Map<String, Object> paramBodyMap = new HashMap<String, Object>();
		paramBodyMap.put("id",id);
		String urlrequest = erpApi + "/order/useraccessory/download";
		String res=HttpUtils.doPost(urlrequest,paramBodyMap);
		R rs = JsonUtils.string2Object(res, R.class);
		String accessoryUrl = rs.get("accessoryUrl").toString();
		String name = rs.get("name").toString();
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		HttpURLConnection conn = null;
		try {
			request.setCharacterEncoding("UTF-8");
			response.setContentType("application/octet-stream");
			// 清除response中的缓存
			response.reset();
			// 根据网络文件地址创建URL
			URL url = new URL(accessoryUrl);
			// 获取此路径的连接
			conn = (HttpURLConnection) url.openConnection();
			// 获取文件大小
			Long fileLength = conn.getContentLengthLong();
			response.setHeader("Content-disposition",
					"attachment; filename=" + URLEncoder.encode(name, "UTF-8"));
			response.setHeader("Content-Length", String.valueOf(fileLength));
			// 构造读取流
			bis = new BufferedInputStream(conn.getInputStream());
			// 构造输出流
			bos = new BufferedOutputStream(response.getOutputStream());
			byte[] buff = new byte[1024];
			int bytesRead;
			// 每次读取缓存大小的流，写到输出流
			while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
				bos.write(buff, 0, bytesRead);
			}
			// 将所有的读取的流返回给客户端
			response.flushBuffer();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (bos != null) {
				try {
					bos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (bis != null) {
				try {
					bis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (conn != null) {
				conn.disconnect();
			}
		}
	}
}
